<?php
require_once('db.php');
require_once('utils.php');

session_start();

if (isset($_POST['send'])) {
	$user = $_POST['user'];
	$email = $_POST['email'];
	$pass = $_POST['pass'];
	$pass2 = $_POST['pass2'];
	
	$error = "";
	
	if(!preg_match("/^[a-z_][a-z0-9_]{2,}$/i", $user))
	{
		$error .= "<li>El usuario debe cumplir la siguiente expresi&oacute;n regular: /[a-z_][a-z0-9_]{2,}$/i</li>";
    }
	if(preg_match("/^(css|js|avatar|img|svg)$/", $user))
	{
		$error .= "<li>El nombre de usuario es incorrecto, utiliza otro</li>";
    }
    $name = know_user_attr($user, "name");
    if(!($name == 'img/none.png'))
        $error .= "<li>El usuario ".$user." ya está registrado</li>";
	
	if(!check_email_address($email))
	{
		$error .= "<li>La direcci&oacute;n de email debe cumplir el RFC 2822</li>";
	}
	
	if($pass != $pass2)
	{
		$error .= "<li>Las contrase&ntilde;as no coinciden</li>";
	}
	
	if(strlen($pass) < 5)
	{
		$error .= "<li>La contrase&ntilde;a es demasiado corta</li>";
	}
	if(!empty($error))
	{
		$error = "<ul>$error</ul>";
	} else {
		// register!
		$q = sprintf("insert into users (name, email, password, register_date, karma, role) values ('%s', '%s', '%s', NOW(), 0, 1)",
		mysql_real_escape_string($user), mysql_real_escape_string($email), mysql_real_escape_string(md5($pass)));
		$res = mysql_query($q);
		$registered = true;
	}
}

?>
<!DOCTYPE html 
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
 <head>
  <title>Sweetter 2.0 - Registro</title>
  <link rel="stylesheet" type="text/css" href="css/estilo.css" />
  <link rel="icon" href="img/favicon.ico" type="image/vnd.microsoft.icon">
  <meta http-equiv=content-type content="text/html; charset=UTF-8">
 </head>
 <body>
<?php show_header("Sweetter 2.0 - Registro"); ?>

   <p>Registro</p>

<?php
if (!empty($error)) {
	echo '<div class="error">'.$error.'</div>';
} elseif($registered == true) {
	echo "<div class=\"success\">Usuario registrado, <a href=\"index.php?quit\">entra aqu&iacute;</a></div>";
}

if(!($registered == true))
{
?>

   <form action="register.php" method="post">
     <label for="usuario">Usuario:</label><br />
     <input type="text" name="user" value="" /><br />
     <label for="email">Email:</label><br />
     <input type="text" name="email" value="" /><br />
     <label for="pass">Contrase&ntilde;a:</label><br />
     <input type="password" name="pass" value="" /><br />
     <label for="pass">Verificar contrase&ntilde;a:</label><br />
     <input type="password" name="pass2" value="" /><br />
     <input type="submit" name="send" value="Crear" />
   </form>

<?php
}

pie(); ?>

 </body>
</html>

